package org.lds.message.center.plugin.core.kafka;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lds.message.center.common.util.JsonUtil;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
public class KafkaProducer {
    private final KafkaTemplate<String, String> kafkaTemplate;

    public boolean send(String topic, Object message) {
        if (StringUtils.isEmpty(topic) || Objects.isNull(message)) return false;

        String value = JsonUtil.toJson(message);
        if (StringUtils.isEmpty(value)) return false;

        try {
            kafkaTemplate.send(topic, value);
            return true;
        } catch (Exception e) {
            log.error("生产消息. topic={} value={}", topic, value, e);
            return false;
        }
    }

    public boolean send(String topic, String key, Object message) {
        if (StringUtils.isEmpty(topic) || StringUtils.isEmpty(key) || Objects.isNull(message)) return false;

        String value = JsonUtil.toJson(message);
        if (StringUtils.isEmpty(value)) return false;

        try {
            log.info("开始发送 topic={} key={} value={}", topic, key, value);
            kafkaTemplate.send(topic, key, JsonUtil.toJson(message));
            return true;
        } catch (Exception e) {
            log.error("send error", e);
            return false;
        }
    }
}
